/**
 * Created by lvlq on 16/2/28.
 */
var csv = require("csv");
var sequelize = Util("sequelize");
var index = function (req, res) {
    var aid = req.query.aid || 1;
    var page = parseInt(req.query.page) || 1;
    var step = parseInt(req.query.step) || 10;
    var start = parseInt((page - 1) * step);
    var return_data = {
        allpage: 0,
        page: page,
        data: [],
        aname: "",
        count: 0,
        aid: aid,
        step: step,
        active: []
    };

    var UserList = M("index.userList");
    var ActiveList = M("index.activeList");

    ActiveList.findAll().then(function (data) {
        return_data.active = data;
        return ActiveList.find({
            where: {
                id: aid
            }
        })
    }).then(function (data) {
        if (!data) throw new Error("error");

        return_data.aname = data.name;

        return UserList.findAndCountAll({
            where: {
                aid: aid
            },
            limit: step,
            offset: start
        });
    }).then(function (data) {
        return_data.count = data.count;
        return_data.allpage = Math.ceil((data.count) / step);
        return_data.data = data.rows;
        res.render("admin.html", return_data);
    }).catch(function (err) {
        res.json({"err": err.message});
    });

};

var exportCSV = function (req, res) {
    var UserList = M("index.userList");
    var ActiveList = M("index.activeList");

    var aid = req.query.aid;
    var alldata = [];
    UserList.findAll({
        where: {
            aid: aid
        },
        attributes: ["id", "name", "phone", "address", "pname", "img_url", "ac_code", "createdAt", sequelize.fn("date_format", sequelize.col('createdAt'), '%Y-%m-%d %H:%m:%s')]
    }).then(function (data) {
        alldata = data;
        var title = ["id", "姓名", "手机号", "地址", "奖品名", "图片链接", "数码", "创建时间"];
        alldata.unshift(title);

        return ActiveList.find({
            where: {
                id: aid
            }
        });
    }).then(function (data) {
        var name = encodeURI(data.name + '获奖数据');
        res.setHeader('Content-disposition', 'attachment; filename=' + name + '.csv');
        res.writeHead(200, {'Content-Type': 'text/csv'});
        csv.stringify(alldata)
            .pipe(res);
    });
};


module.exports = {
    index: index,
    exportCSV: exportCSV
};